package logic

import (
	"context"
	"errors"
	"zero-cloud-disk/api/helper"
	"zero-cloud-disk/api/internal/svc"
	"zero-cloud-disk/api/internal/types"
	"zero-cloud-disk/api/models"
	"zero-cloud-disk/service/redis"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserRegisterLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserRegisterLogic {
	return &UserRegisterLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserRegisterLogic) UserRegister(req *types.UserRegisterReq) (resp string, err error) {
	// 获取code
	value := redis.Get(req.Email)
	if value == "" {
		return "", errors.New("验证码已过期, 请重新发送")
	}
	if value != req.Code {
		return "", errors.New("验证码错误")
	}
	// 判断邮箱是否注册
	emailCount, err := l.svcCtx.Engine.Where("email = ?", req.Email).Count(new(models.UserBasic))
	if err != nil {
		return "", err
	}
	if emailCount > 0 {
		return "", errors.New("邮箱已被注册")
	}
	// 判断用户名是否注册
	count, err := l.svcCtx.Engine.Where("name = ?", req.Name).Count(new(models.UserBasic))
	if err != nil {
		return "", err
	}
	if count > 0 {
		return "", errors.New("用户名已存在")
	}
	user := &models.UserBasic{
		Identity: helper.GetUUID(),
		Name:     req.Name,
		Password: helper.GetMd5(req.Password),
		Email:    req.Email,
	}

	if _, err := l.svcCtx.Engine.Insert(user); err != nil {
		return "", err
	}
	err = redis.Del(req.Email)
	if err != nil {
		return "", err
	}
	return "", nil
}
